import { asyncRoutes, constantRoutes } from '@/router'
import { getRoleMenus } from '@/api/role'
import declarationComponent from '@/router/modules/declarationComponent'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes).concat(asyncRoutes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      let accessedRoutes
      getRoleMenus().then(response => {
        var list = response.data.menus
        list = renderReplace(list)
        if (roles.includes(1)) {
          accessedRoutes = list || []
        } else {
          accessedRoutes = filterAsyncRoutes(list, roles)
        }
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      })
    })
  }
}

// 递归替换组件
function renderReplace(routeData) {
  routeData.forEach((item, index, routeData) => {
    if (!item.component) {
      console.error('Not Found item.component Props!!')
      return routeData
    }

    // 替换
    // routeData[index].component = routes[routeData[index].component]
    routeData[index].component = findComponent(routeData[index].component)

    if (routeData[index].children && routeData[index].children.length > 0) {
      return renderReplace(routeData[index].children)
    }
  })

  return routeData
}

// 寻找组件，与 declarationComponent 的结构匹配
function findComponent(path) {
  var routeComponent = declarationComponent
  path.replace('@/', '').split('/').forEach((item, index, pathArray) => {
    if (!routeComponent[item]) {
      console.error('Not Found Component! 请确认 declarationComponent 中声明了该组件路由', item)
    } else {
      routeComponent = routeComponent[item]
    }
  })
  return routeComponent
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
